package info.liuxing.okhttp.interceptor;

import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.internal.http.HttpHeaders;
import okhttp3.internal.http.RealResponseBody;
import okio.GzipSource;
import okio.Okio;

import java.io.IOException;

/**
 * UnGzipResponseInterceptor
 *
 * @author liuxing (SE)
 * @summary UnGzipResponseInterceptor
 * @Copyright (c) 2017, Lianjia Group All Rights Reserved.
 * @since 2017-12-01 09:42
 */
public class UnGzipResponseInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);

        if ("gzip".equalsIgnoreCase(response.header("Content-Encoding"))
                && HttpHeaders.hasBody(response)) {
            GzipSource responseBody = new GzipSource(response.body().source());
            Headers strippedHeaders = response.headers().newBuilder()
                    .removeAll("Content-Encoding")
                    .removeAll("Content-Length")
                    .build();

            Response.Builder responseBuilder = response.newBuilder();
            responseBuilder.headers(strippedHeaders);
            String contentType = response.header("Content-Type");
            responseBuilder.body(new RealResponseBody(contentType, -1L, Okio.buffer(responseBody)));
            return responseBuilder.build();
        }

        return response;
    }
}
